import React, { useRef, useEffect, useMemo, useState, useCallback } from 'react';
import { useTerminalStore, useProjectStore } from '../../stores';
import { globalPlayer } from 'python-player';
import globalEventManager, { PYTHON_EVENTS, TERMINAL_EVENTS } from '../../utils/eventManager';
import { FaTrash, FaDesktop, FaClock, FaCalendar } from 'react-icons/fa6';
import { iconMapping } from '../../utils';
import styles from './Terminal.module.css';

const Terminal = ({ 
  onTerminalReady,
  isVisible = true
}) => {
  const outputContentRef = useRef(null);
  const inputRef = useRef(null);
  const terminalStore = useTerminalStore();
  const projectStore = useProjectStore();
  
  const { outputLines } = terminalStore;
  // 直接监听状态变化事件，而不是通过 store
  const [isRunning, setIsRunning] = useState(false);
  
  // 输入相关状态
  const [isWaitingForInput, setIsWaitingForInput] = useState(false);
  const [currentInput, setCurrentInput] = useState('');
  const [inputPrompt, setInputPrompt] = useState('');

  // 处理输入请求 - 使用全局事件
  const handleInputRequest = useCallback((prompt) => {
    setInputPrompt(prompt);
    setCurrentInput('');
    
    // 确保终端可见
    terminalStore.showTerminal();
    
    // 触发显示输入框事件
    globalEventManager.emit(TERMINAL_EVENTS.SHOW_INPUT, { prompt });
  }, [terminalStore]);

  // 自动调整textarea高度
  const adjustTextareaHeight = useCallback(() => {
    if (inputRef.current) {
      inputRef.current.style.height = 'auto';
      inputRef.current.style.height = inputRef.current.scrollHeight + 'px';
    }
  }, []);

  // 监听输入变化，自动调整高度
  useEffect(() => {
    if (isWaitingForInput) {
      adjustTextareaHeight();
    }
  }, [currentInput, isWaitingForInput, adjustTextareaHeight]);

  // 处理输入提交
  const handleInputSubmit = useCallback((e) => {
    e.preventDefault();
    
    if (globalPlayer && globalPlayer.handleInput) {
      // 将完整的prompt+用户输入添加到输出历史中
      const fullInputLine = inputPrompt + currentInput;
      terminalStore.addOutputLine(fullInputLine, 'input-line');
      
      // 触发输入响应事件
      globalEventManager.emit(PYTHON_EVENTS.INPUT_RESPONSE, {
        prompt: inputPrompt,
        input: currentInput,
        fullLine: fullInputLine
      });
      
      const success = globalPlayer.handleInput(currentInput);
      if (success) {
        setIsWaitingForInput(false);
        setCurrentInput('');
        setInputPrompt(''); // 清空prompt，因为输入已完成
      }
    }
  }, [currentInput, inputPrompt, terminalStore]);

  // 使用事件管理器订阅各种事件
  useEffect(() => {
    // 监听 Python 状态变化
    const unsubscribeStatusChange = globalEventManager.on(PYTHON_EVENTS.STATUS_CHANGE, (status) => {
      setIsRunning(status === 'running');
    });
    
    // 监听输入请求事件
    const unsubscribeInputRequest = globalEventManager.on(PYTHON_EVENTS.INPUT_REQUEST, handleInputRequest);
    
    // 订阅终端事件
    const unsubscribeShowInput = globalEventManager.on(TERMINAL_EVENTS.SHOW_INPUT, ({ prompt }) => {
      setIsWaitingForInput(true);
      setInputPrompt(prompt);
      setCurrentInput('');
    });
    
    const unsubscribeHideInput = globalEventManager.on(TERMINAL_EVENTS.HIDE_INPUT, () => {
      setIsWaitingForInput(false);
      setCurrentInput('');
      setInputPrompt('');
    });
    
    const unsubscribeFocusInput = globalEventManager.on(TERMINAL_EVENTS.FOCUS_INPUT, () => {
      setTimeout(() => {
        if (inputRef.current) {
          inputRef.current.focus();
          const length = inputRef.current.value.length;
          inputRef.current.setSelectionRange(length, length);
        }
      }, 50);
    });
    
    return () => {
      unsubscribeStatusChange();
      unsubscribeInputRequest();
      unsubscribeShowInput();
      unsubscribeHideInput();
      unsubscribeFocusInput();
    };
  }, [handleInputRequest]);

  // 监听运行状态变化，当停止时清理输入状态
  useEffect(() => {
    if (!isRunning && isWaitingForInput) {
      // 代码停止时，先将prompt添加到输出历史，然后清理输入状态
      if (inputPrompt) {
        terminalStore.addOutputLine(inputPrompt, 'normal');
      }
      // 使用全局事件隐藏输入框
      globalEventManager.emit(TERMINAL_EVENTS.HIDE_INPUT);
    }
  }, [isRunning, isWaitingForInput, inputPrompt, terminalStore]);

  // 自动聚焦到输入框 - 使用全局事件
  useEffect(() => {
    if (isWaitingForInput) {
      // 延迟触发聚焦事件，确保组件完全渲染
      const timer = setTimeout(() => {
        globalEventManager.emit(TERMINAL_EVENTS.FOCUS_INPUT);
      }, 100);
      return () => clearTimeout(timer);
    }
  }, [isWaitingForInput]);

  // 渲染输出内容 - 直接使用行级别数据
  const renderedOutput = useMemo(() => {
    return outputLines.map((line) => {
      if (line.type === 'error') {
        return (
          <div key={line.id} className={styles.inlineError}>
            <div className={styles.inlineErrorHeader}>Python 运行错误</div>
            <div className={styles.inlineErrorContent}>
              {line.errorInfo?.line && (
                <span className={styles.errorLocation}>
                  行 {line.errorInfo.line}{line.errorInfo.column && `, 列 ${line.errorInfo.column}`}:
                </span>
              )}
              <span className={styles.errorMessage}>{line.errorInfo?.message || line.content}</span>
            </div>
          </div>
        );
      } else if (line.type === 'warning') {
        return (
          <div key={line.id} className={styles.inlineWarning}>
            <div className={styles.inlineWarningHeader}>JavaScript 执行警告</div>
            <div className={styles.inlineWarningContent}>{line.content}</div>
          </div>
        );
      } else if (line.type === 'system') {
        return (
          <div key={line.id} className={styles.inlineSystem}>
            <div className={styles.inlineSystemMessage}>
              <div className={styles.iconTitle}>
                {iconMapping.renderSystemIcon(line.iconType, styles.systemIcon)}
                <span className={styles.systemTitle}>{line.title}</span>
              </div>
              <div className={styles.timeContainer}>
                {line.duration && (
                  <div className={styles.durationSection}>
                    <FaClock className={styles.timeIcon} />
                    <span className={styles.timeLabel}>耗时</span>
                    <span className={styles.durationBadge}>{line.duration}</span>
                  </div>
                )}
                {line.timestamp && (
                  <div className={styles.timestampSection}>
                    <FaCalendar className={styles.timeIcon} />
                    <span className={styles.timeLabel}>时间</span>
                    <span className={styles.timestampBadge}>{line.timestamp}</span>
                  </div>
                )}
              </div>
            </div>
          </div>
        );
      } else if (line.type === 'input-line') {
        // 完整的输入行（prompt + 用户输入）
        return (
          <div key={line.id} className={styles.inputLineOutput}>
            {line.content}
          </div>
        );
      } else {
        // 普通输出
        return (
          <div key={line.id} className={styles.normalOutput}>
            {line.content}
          </div>
        );
      }
    });
  }, [outputLines]);

  // 自动滚动到底部
  useEffect(() => {
    if (outputContentRef.current && outputLines.length > 0) {
      const element = outputContentRef.current;
      element.scrollTop = element.scrollHeight;
      
      // 双重保险：强制滚动到最底部
      const maxScrollTop = element.scrollHeight - element.clientHeight;
      if (maxScrollTop > 0) {
        element.scrollTop = maxScrollTop;
      }
    }
  }, [outputLines]);

  // 初始化终端引用
  useEffect(() => {
    const timer = setTimeout(() => {
      if (outputContentRef.current && onTerminalReady) {
        onTerminalReady(outputContentRef);
      }
    }, 0);
    
    return () => clearTimeout(timer);
  }, []); // 只在组件挂载时执行一次

  return (
    <div className={`${styles.terminal} ${!isVisible ? styles.terminalHidden : ''}`}>
      <div className={styles.terminalHeader}>
        <div className={styles.terminalTitle}>
          <FaDesktop className={styles.terminalIcon} />
          控制台
        </div>
        <div className={styles.terminalControls}>
          <button
            className={styles.terminalControlBtn}
            onClick={terminalStore.clearOutput}
            title="清空输出"
          >
            <FaTrash />
          </button>
        </div>
      </div>
      <div className={styles.terminalContent} ref={outputContentRef}>
        {renderedOutput}
        {outputLines.length === 0 && (
          <div className={styles.terminalPlaceholder}>
            {isRunning ? '程序运行中...' : '运行代码查看输出结果...'}
          </div>
        )}
        
        {/* 输入行 */}
        {isWaitingForInput && (
          <div className={styles.inputLine}>
            <span className={styles.inputPrompt}>{inputPrompt}</span>
            <textarea
              ref={inputRef}
              value={currentInput}
              onChange={(e) => setCurrentInput(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                  e.preventDefault();
                  handleInputSubmit(e);
                }
              }}
              className={styles.inputField}
              placeholder=""
              rows={1}
              autoFocus
              autoComplete="off"
              spellCheck="false"
              style={{ minHeight: '1.5em', maxHeight: '200px' }}
            />
          </div>
        )}
      </div>
    </div>
  );
};

export default Terminal;
